#include "RelCommand.h"
#include "PhnqletManager.h"
#include "I18n.h"
#include <iostream>
#include <fstream>
#include "kit.h"

using namespace std;

namespace phnq
{
	namespace phnqlets
	{
		static phnq::kit::log::Logger *log = phnq::kit::log::Logger::get("phnq::phnqlets::RelCommand");
		
		void RelCommand::execute(string relPath, map<string,string> params, processor_response *response)
		{
			response->clientCacheDuration = 60 * 60 * 24 * 365; // one year
			
			size_t slash1Idx = relPath.find_first_of("/");
			if(slash1Idx == string::npos)
			{
				response->status = STATUS_BAD_REQUEST;
				return;
			}
			
			string cacheKey = relPath.substr(0, slash1Idx);

			size_t slash2Idx = relPath.find_first_of("/", slash1Idx+1);
			if(slash2Idx == string::npos)
			{
				response->status = STATUS_BAD_REQUEST;
				return;
			}

			string type = relPath.substr(slash1Idx+1, slash2Idx-slash1Idx-1);

			Phnqlet *p = PhnqletManager::getInstance()->get(type);
			if(p)
			{
				string path = I18n::getL10nPath(relPath.substr(slash2Idx+1));
				if(path.length() == 0)
				{
					response->status = STATUS_BAD_REQUEST;
					return;
				}

				string onDiskPath = p->getDir() + "/" + path;
				if(fopen (onDiskPath.c_str(),"r"))
				{
					response->bodyStream = new ifstream(onDiskPath.c_str());
				}
				else
				{
					response->status = STATUS_NOT_FOUND;
				}
			}
			else
			{
				response->status = STATUS_NOT_FOUND;
			}
		}
	}
}
